package com.fulihui.wgj.admin.integration.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.fulihui.common.builder.web.JsonResultBuilder;
import com.fulihui.common.constants.PlaceholderConstants;
import com.fulihui.common.conv.BeanConv;
import com.fulihui.common.enums.CustomMsgTypeEnum;
import com.fulihui.common.enums.SubReplyUseTypeEnum;
import com.fulihui.common.result.rpc.BaseResult;
import com.fulihui.common.result.rpc.SimpleResult;
import com.fulihui.common.result.web.Result;
import com.fulihui.common.util.DateUtils;
import com.fulihui.common.util.RpcResultCheckUtil;
import com.fulihui.weixinsdk.result.user.UserInfoGetResult;
import com.fulihui.wgj.admin.api.material.vo.MaterialNewsItemVO;
import com.fulihui.wgj.admin.api.material.vo.MaterialNewsVO;
import com.fulihui.wgj.admin.api.subscribereply.request.*;
import com.fulihui.wgj.admin.api.subscribereply.vo.SubscribeReplyAdvertVO;
import com.fulihui.wgj.admin.api.subscribereply.vo.SubscribeReplyVO;
import com.fulihui.wgj.admin.config.properties.AdminProperties;
import com.fulihui.wgj.admin.integration.MaterialServiceClient;
import com.fulihui.wgj.admin.integration.SubscribeAdverseServiceClient;
import com.fulihui.wgj.admin.integration.SubscribeReplyClient;
import com.fulihui.wgj.admin.weixin.WeiXinCustomerMsgManage;
import com.fulihui.wgj.admin.weixin.WeiXinUserManage;
import com.fulihui.wgj.facade.dto.WxMaterialDTO;
import com.fulihui.wgj.facade.dto.WxSubscribeReplyRuleDTO;
import com.fulihui.wgj.facade.request.PrimaryKeyRequest;
import com.fulihui.wgj.facade.request.reply.ReplyRuleEnableOrDisableRequest;
import com.fulihui.wgj.facade.request.reply.WxSubscribeReplyRuleQueryRequest;
import com.fulihui.wgj.facade.request.reply.WxSubscribeReplyRuleSaveRequest;
import com.fulihui.wgj.facade.request.reply.WxSubscribeReplyRuleUpdateRequest;
import com.fulihui.wgj.facade.service.reply.WxSubscribeReplyService;
import com.google.common.collect.Lists;
import org.near.toolkit.common.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;

import static com.fulihui.common.enums.SubReplyTypeEnum.*;
import static com.fulihui.common.error.Errors.Commons.REQUEST_PARAMETER_ERROR;

/**
 * @author: Levon
 * @date: 2018-07-26 13:59
 */
@Service
public class SubscribeReplyClientImpl implements SubscribeReplyClient {

    @Reference(version = "1.0.0")
    private WxSubscribeReplyService replyService;

    @Autowired
    private MaterialServiceClient materialServiceClient;

    @Autowired
    private WeiXinCustomerMsgManage weiXinCustomerMsgManage;

    @Autowired
    private WeiXinUserManage weiXinUserManage;

    @Autowired
    private SubscribeAdverseServiceClient subscribeAdverseServiceClient;

    @Autowired
    private AdminProperties adminProperties;

    @Override
    public Result<SubscribeReplyVO> queryDefaultReply(SubscribeReplyRequest replyReq) {

        WxSubscribeReplyRuleQueryRequest request = new WxSubscribeReplyRuleQueryRequest();
        request.setAppId(replyReq.getAppId());
        request.setUseType(SubReplyUseTypeEnum.DEFAULT.getValue());
        SimpleResult<List<WxSubscribeReplyRuleDTO>> result = replyService.queryReplyRule(request);

        SubscribeReplyVO replyVO = new SubscribeReplyVO();
        replyVO.setUseType(SubReplyUseTypeEnum.DEFAULT.getValue());
        if (RpcResultCheckUtil.isSuccess(result)) {
            List<WxSubscribeReplyRuleDTO> datas = result.getData();
            if (!CollectionUtils.isEmpty(datas)) {
                //默认回复
                WxSubscribeReplyRuleDTO replyRuleDTO = datas.get(0);
                replyVO = BeanConv.copy(replyRuleDTO, replyVO.getClass());

                replyVO.setReplyType(replyRuleDTO.getReplyType());
                replyVO.setUseful(replyRuleDTO.getUseful());
                if (replyRuleDTO != null) {
                    parse(replyVO, replyRuleDTO);
                }
            } else {
                return JsonResultBuilder.succ(null);
            }
        }
        return JsonResultBuilder.succ(replyVO);
    }

    @Override
    public Result<List<SubscribeReplyVO>> querySpecificReply(SubscribeReplyRequest replyReq) {

        WxSubscribeReplyRuleQueryRequest request = new WxSubscribeReplyRuleQueryRequest();
        request.setAppId(replyReq.getAppId());
        request.setUseType(SubReplyUseTypeEnum.SPECIFIC.getValue());
        SimpleResult<List<WxSubscribeReplyRuleDTO>> result = replyService.queryReplyRule(request);

        List<SubscribeReplyVO> replyVOs = Lists.newArrayList();

        if (RpcResultCheckUtil.isSuccess(result)) {
            List<WxSubscribeReplyRuleDTO> datas = result.getData();
            if (!CollectionUtils.isEmpty(datas)) {
                for (WxSubscribeReplyRuleDTO data : datas) {
                    SubscribeReplyVO replyVO = BeanConv.copy(data, SubscribeReplyVO.class);
                    parse(replyVO, data);
                    replyVOs.add(replyVO);
                }
            } else {
                return JsonResultBuilder.succ(null);
            }
        }
        return JsonResultBuilder.succ(replyVOs);
    }

    @Override
    public Result<Boolean> save(SubscribeReplySaveRequest request) {

        WxSubscribeReplyRuleSaveRequest saveRequest = BeanConv.copy(request, WxSubscribeReplyRuleSaveRequest.class);
        saveRequest.setAppId(request.getAppId());
        if (text.getValue() == request.getReplyType()) {
            saveRequest.setReplyContent(request.getTextContent());
        } else if (image.getValue() == request.getReplyType()) {
            saveRequest.setReplyContent(request.getMediaId());
        } else if (news.getValue() == request.getReplyType()) {
            saveRequest.setReplyContent(request.getMediaId());
        }
        BaseResult baseResult = replyService.saveReplyRule(saveRequest);
        if (RpcResultCheckUtil.isSuccess(baseResult)) {
            return JsonResultBuilder.succ(true);
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }


    @Override
    public Result<Boolean> update(SubscribeReplyUpdateRequest request) {
        WxSubscribeReplyRuleUpdateRequest updateRequest = BeanConv.copy(request, WxSubscribeReplyRuleUpdateRequest.class);
        updateRequest.setAppId(request.getAppId());
        if (text.getValue() == request.getReplyType()) {
            updateRequest.setReplyContent(request.getTextContent());
        } else if (image.getValue() == request.getReplyType()) {
            updateRequest.setReplyContent(request.getMediaId());
        } else if (news.getValue() == request.getReplyType()) {
            updateRequest.setReplyContent(request.getMediaId());
        }
        BaseResult baseResult = replyService.updateReplyRuleById(updateRequest);
        if (RpcResultCheckUtil.isSuccess(baseResult)) {
            return JsonResultBuilder.succ(true);
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }

    @Override
    public Result<Boolean> delete(Integer id) {
        PrimaryKeyRequest request = new PrimaryKeyRequest();
        request.setId(id);
        BaseResult result = replyService.deleteReplyRuleById(request);
        if (RpcResultCheckUtil.isSuccess(result)) {
            return JsonResultBuilder.succ(true);
        }
        return JsonResultBuilder.fail(result.getErrcode(), result.getErrmsg());
    }


    @Override
    public Result<Boolean> enableOrDisabled(Integer id, Integer useful) {
        ReplyRuleEnableOrDisableRequest request = new ReplyRuleEnableOrDisableRequest();
        request.setId(id);
        request.setUseful(useful);
        BaseResult baseResult = replyService.enableOrDisable(request);
        if (RpcResultCheckUtil.isSuccess(baseResult)) {
            return JsonResultBuilder.succ(true);
        }
        return JsonResultBuilder.fail(baseResult.getErrcode(), baseResult.getErrmsg());
    }

    @Override
    public Result<SubscribeReplyVO> preview(SubscribeReplyQueryRequest replyReq) {

        PrimaryKeyRequest request = new PrimaryKeyRequest();
        request.setId(replyReq.getId());
        SimpleResult<WxSubscribeReplyRuleDTO> simpleResult = replyService.queryRuleById(request);
        SubscribeReplyVO replyVO = new SubscribeReplyVO();
        replyVO.setUseType(SubReplyUseTypeEnum.DEFAULT.getValue());
        if (RpcResultCheckUtil.isSuccess(simpleResult)) {
            WxSubscribeReplyRuleDTO replyRuleDTO = simpleResult.getData();
            if (replyRuleDTO != null) {
                replyVO = BeanConv.copy(replyRuleDTO, replyVO.getClass());
                replyVO.setReplyType(replyRuleDTO.getReplyType());
                replyVO.setUseful(replyRuleDTO.getUseful());
                if (replyRuleDTO != null) {
                    parse(replyVO, replyRuleDTO);
                }
            } else {
                return JsonResultBuilder.succ(null);
            }
        }
        return JsonResultBuilder.succ(replyVO);
    }

    @Override
    public Result<Boolean> sendPre(SubscribeReplySendPreRequest replyReq) {
        WxSubscribeReplyRuleDTO data = null;
        if (replyReq.getId() == null) {
            data = new WxSubscribeReplyRuleDTO();
            //如果为空，说明是未保存预览，直接填入内容
            Integer msgType = replyReq.getMsgType();
            String mediaid = replyReq.getMediaid();
            String textContent = replyReq.getTextContent();
            if (msgType == null) {
                if (news.getValue() == msgType || image.getValue() == msgType) {
                    if (StringUtils.isEmpty(mediaid)) {
                        return JsonResultBuilder.fail(REQUEST_PARAMETER_ERROR.getErrcode(), REQUEST_PARAMETER_ERROR.getErrmsg());
                    }
                } else if (text.getValue() == msgType) {
                    if (StringUtils.isEmpty(textContent)) {
                        return JsonResultBuilder.fail(REQUEST_PARAMETER_ERROR.getErrcode(), REQUEST_PARAMETER_ERROR.getErrmsg());
                    }
                }
            }
            data.setReplyType(msgType);
            data.setMediaId(mediaid);
            data.setReplyContent(textContent);
        } else {
            PrimaryKeyRequest request = new PrimaryKeyRequest();
            request.setId(replyReq.getId());
            SimpleResult<WxSubscribeReplyRuleDTO> simpleResult = replyService.queryRuleById(request);
            if (RpcResultCheckUtil.isSuccess(simpleResult)) {
                data = simpleResult.getData();
            }
        }

        String replyContent = data.getReplyContent();
        Integer replyType = data.getReplyType();
        String msgType = null;
        String mediaid = null;
        if (news.getValue() == replyType) {
            msgType = CustomMsgTypeEnum.mpnews.getCode();
            mediaid = data.getMediaId();
        } else if (image.getValue() == replyType) {
            msgType = CustomMsgTypeEnum.image.getCode();
            mediaid = data.getMediaId();
        } else if (text.getValue() == replyType) {
            msgType = CustomMsgTypeEnum.text.getCode();
            //替换固定字符串消息
            UserInfoGetResult userDetail = weiXinUserManage.getUserDetail(replyReq.getAppId(), replyReq.getOpenId());
            if (userDetail != null && userDetail.getUserInfo() != null) {
                replyContent = replyContent.replaceAll(PlaceholderConstants.NICK_NAME_PLACEHOLDER, userDetail.getUserInfo().getNickname());
            }
            List<SubscribeReplyAdvertVO> advertVOS = subscribeAdverseServiceClient.queryAdvertList(replyReq.getAppId());
            if (!CollectionUtils.isEmpty(advertVOS)) {
                Collections.shuffle(advertVOS);
                SubscribeReplyAdvertVO replyAdvert = advertVOS.get(0);
                replyContent = replyContent.replaceAll(PlaceholderConstants.ADVERT, "\n" + replyAdvert.getAdvert());
            } else {
                replyContent = replyContent.replaceAll(PlaceholderConstants.ADVERT, StringUtil.EMPTY_STRING);
            }
        }
        Result<Boolean> result = weiXinCustomerMsgManage.sendText(replyReq.getAppId(), replyReq.getOpenId(),
                msgType, replyContent, mediaid);
        return result;
    }

    private SubscribeReplyVO parse(SubscribeReplyVO replyVO, WxSubscribeReplyRuleDTO replyRuleDTO) {
        Integer replyType = replyRuleDTO.getReplyType();
        if (news.getValue() == replyType) {
            MaterialNewsVO newsVO = new MaterialNewsVO();
            String jsonContent = replyRuleDTO.getReplyContent();
            WxMaterialDTO material = JSON.parseObject(jsonContent, WxMaterialDTO.class);
            newsVO.setMediaId(material.getMediaId());
            newsVO.setUpdateTime(DateUtils.format(material.getUpdateTime(), DateUtils.noSecondFormat));
            String items = material.getContent();
            List<MaterialNewsItemVO> newsItemVOS = materialServiceClient.parse(items);
            newsVO.setItems(newsItemVOS);
            replyVO.setNewsInfo(newsVO);
        } else {
            String jsonContent = replyRuleDTO.getReplyContent();
            if (image.getValue() == replyType) {
                WxMaterialDTO material = JSON.parseObject(jsonContent, WxMaterialDTO.class);
                replyVO.setImgUrl(adminProperties.getImgproxy() + material.getImageUrl());
            }
            if (text.getValue() == replyType) {
                replyVO.setTextContent(replyRuleDTO.getReplyContent());
            }
        }
        return replyVO;
    }
}
